package com.doform.android.xianggucheng.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.bean.ClientCategoryBean;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.utils.Constans;
import com.doform.android.xianggucheng.widget.DividerItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * 作者 Y_MS
 * Created by ${APEN} on 2017/6/7.
 * GitHub：https://github.com/cxydxpx
 */

public class ListClientCategoryActivity extends BaseTitleActivity implements OnRefreshListener, OnLoadmoreListener {

    public static final int PAGE_CONTENT_INIT = 1;
    private int mCurrentPage = PAGE_CONTENT_INIT;

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.tv_empty)
    TextView mEmpty;

    private List<ClientCategoryBean.ListBean> mDatas = new ArrayList<>();
    private CommonAdapter mCommonAdapter;

    @Override
    protected void showView() {
        titleBar.setTextTitle("客户分类");
    }

    @Override
    protected int layoutResId() {
        return R.layout.activity_client_category;
    }

    @Override
    protected void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
    }

    @Override
    protected void updateData() {
        super.updateData();
        refresh();
    }

    private void refresh() {
        mCurrentPage = PAGE_CONTENT_INIT;
        getDataForService(mCurrentPage);
    }

    private void getDataForService(int mCurrentPage) {
        HttpManager.instance()
                .getClientCategory2(String.valueOf(mCurrentPage))
                .subscribe(new ErrorHandleSubscriber<ClientCategoryBean>() {
                    @Override
                    public void onNext(@NonNull ClientCategoryBean clientCategoryBean) {
                        jsonData(clientCategoryBean.getList());
                    }
                });
    }

    private void getDataForService2(int mCurrentPage) {
        HttpManager.instance()
                .getClientCategory2(String.valueOf(mCurrentPage))
                .subscribe(new ErrorHandleSubscriber<ClientCategoryBean>() {
                    @Override
                    public void onNext(@NonNull ClientCategoryBean clientCategoryBean) {
                        jsonData(clientCategoryBean.getList());
                    }
                });
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mCurrentPage = PAGE_CONTENT_INIT;
        getDataForService2(mCurrentPage);
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mCurrentPage++;
        getDataForService2(mCurrentPage);
    }

    //    解析数据
    private void jsonData(List<ClientCategoryBean.ListBean> data) {

        if (mCurrentPage == PAGE_CONTENT_INIT) {
            mDatas.clear();
        }

        if (data.size() == 0 || data == null) {
            mCurrentPage--;
            refreshLayout.finishLoadmore();
            return;
        }
        mDatas.addAll(data);
        mCommonAdapter.notifyDataSetChanged();
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
    }

    @Override
    protected void initListener() {

        refreshLayout.setEnableHeaderTranslationContent(false);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadmoreListener(this);

        mCommonAdapter = new CommonAdapter<ClientCategoryBean.ListBean>(this, R.layout.activity_client_category_item, mDatas) {
            @Override
            protected void convert(ViewHolder holder, final ClientCategoryBean.ListBean clientBean, final int position) {
                TextView tv_name = holder.getView(R.id.tv_name);
                tv_name.setText(clientBean.getName());

                holder.getView(R.id.rl_delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDialog(clientBean);
                    }
                });
            }
        };

        mCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                ClientCategoryBean.ListBean dataBean = mDatas.get(position);
                Intent intent = new Intent(ListClientCategoryActivity.this, UpdateClientCategoryActivity.class);
                intent.putExtra(Constans.EXTRA_UPDATE_CLIENT_CATEGORY, dataBean);
                startActivity(intent);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mRecyclerView.setAdapter(mCommonAdapter);
    }

    private void showDialog(final ClientCategoryBean.ListBean clientBean) {
        new AlertDialog.Builder(this)
                .setMessage("该数据删除后将无法恢复，请确认是否要删除?")
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                deleteItem(clientBean);
                            }
                        })
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
    }

    private void deleteItem(final ClientCategoryBean.ListBean clientBean) {
        HttpManager.instance()
                .deleteClientCategory2(clientBean.getId(), clientBean.getGuid())
                .subscribe(new ErrorHandleSubscriber<Integer>() {
                    @Override
                    public void onNext(@NonNull Integer integer) {
                        refresh();
                    }
                });
    }

    @OnClick(R.id.btn_add)
    public void add() {
        startActivity(new Intent(this, NewClientCategoryActivity.class));
    }


}
